<template>
    <div class="content">
        <i class="ivu-icon ivu-icon-ios-add"></i>
        <Form :label-width="200" :model="form" :rules="rules" ref="form">
            <FormItem label="所属分类" prop="sortId">
                <Select
                    v-model="form.sortId"
                    style="width: 200px;margin-right:10px;"
                    clearable
                >
                    <Option v-for="item in sList" :key="item.id" :value="item.id">{{item.name}}</Option>
                </Select>
                <Button @click="handleAddSort">增加分类</Button>
            </FormItem>
            <FormItem label="题型" prop="type">
                <RadioGroup v-model="form.type">
                    <Radio v-for="(item,index) in questionType" :key="index" :label="index">{{ item }}</Radio>
                </RadioGroup>
            </FormItem>
            <FormItem label="难度" prop="difficulty">
                <RadioGroup v-model="form.difficulty">
                    <Radio v-for="(item,index) in questionDifficulty" :key="index" :label="index">{{ item }}</Radio>
                </RadioGroup>
            </FormItem>
            <FormItem label="分数" prop="score">
                <Input
                    style="width: 200px;margin-right:10px;"
                    type="number"
                    v-model="form.score"
                ></Input>
                <span>分</span>
            </FormItem>
            <FormItem label="题干" prop="topic">
                <Input v-model="form.topic" type="textarea" show-word-limit placeholder="" />
            </FormItem>

            <Row v-if="form.type==1||form.type==2">
                <Col span="18">
                <FormItem
                    class="notop"
                    v-for="(opt, index) in form.opts"
                    :label="'答案'+questionOption[index+1]"
                    :key="index"
                    style="margin-top:12px;"
                    :prop="'opts.' + index + '.value'"
                    :rules="{required: form.topicImageArr[index]?false:true, message:'答案不能为空', trigger: 'blur'}"
                >
                    <Input
                        prefix-icon="el-icon-edit-outline"
                        class="answerInput"
                        v-model="opt.value"
                        style="width:60%;"
                    />

                    <Icon v-if="!form.topicImageArr[index]" @click="uploadClick(index)" type="ios-camera" size="33"></Icon>
                    <img v-else :src="form.topicImageArr[index]" class="avact-img" @click="uploadClick(index)" />
                    <Button class="ml10" shape="circle" icon="ios-remove" @click="delOpt(opt,index)"></Button>
                    <Button class="ml10" type="primary" shape="circle" icon="ios-add" @click="addOpt(opt,index)"></Button>
                </FormItem>
                </Col>
                <Col span="3">
                <FormItem label="" prop="xiaoan" v-if="form.type==1" class="nl">
                    <RadioGroup v-model="form.xiaoan">
                        <Radio class="h30" v-for="(item) in form.opts" :key="item.num" :label="item.num">正确答案</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="" prop="xiaocheck" v-if="form.type==2" class="nl">
                    <CheckboxGroup v-model="form.xiaocheck">
                        <Checkbox class="h30" v-for="(item) in form.opts" :key="item.num" :label="item.num">正确答案</Checkbox>
                    </CheckboxGroup>
                </FormItem>
                </Col>
                <Col span="3">
                <!--
                <Icon class="f24" @click="up(type,item,i)" type="ios-arrow-dropup" />
                <Icon class="f24" @click="down(type,item,i)" type="ios-arrow-dropdown" />-->
                </Col>
            </Row>

            <FormItem label="答案" prop="answer" v-if="form.type==4">
                <RadioGroup v-model="form.answer">
                    <Radio :key="0" label="正确">正确</Radio>
                    <Radio :key="1" label="错误">错误</Radio>
                </RadioGroup>
            </FormItem>
            <FormItem label="答案" prop="answer" v-if="form.type!=1&&form.type!=2&&form.type!=4">
                <Input
                    v-model="form.answer"
                    type="textarea"
                ></Input>
                <div>（多个答案以“|”分隔，一个空有多个答案则用“&”分隔）</div>
            </FormItem>

            <FormItem label="解析" prop="analysis">
                <Input
                    type="textarea"
                    v-model="form.analysis"
                ></Input>
            </FormItem>
            <FormItem>
                <div class="submit-footer">
                    <Button type="primary" @click="submit">保存</Button>
                    <Button @click="handleCancel">取消</Button>
                </div>
            </FormItem>
        </Form>
        <Upload
            style="visibility:hidden"
            ref="upload"
            :show-upload-list="false"
            :default-file-list="defaultList"
            :on-success="handleSuccess"
            :headers="headers"
            :max-size="2048"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            type="drag"
            :action="action"
            :format="['jpg','jpeg','png']"
        >
            <a ref="hh"></a>
        </Upload>
    </div>
</template>
<script>
import config from '@/config'
import { questionType, questionDifficulty, questionOption } from '@/libs/enums'
import { sortList, addQuestion, editQuestion, getQuestion, getCheck } from '@/api/questionManage'
import { getToken } from '@/libs/util'
export default {
    props: {
        headers: {
            type: Object,
            default: () => {
                return {
                    Authorization: getToken()
                }
            }
        }
    },
    inject: ['nextPageReload'],
    components: {
    },
    data () {
        return {
            min: 0,
            max: 200,
            picUrl: config.picUrl,
            action: config.uploadUrl,
            nowIndex: 0,
            defaultList: [],
            uploadList: [],
            sList: [],
            questionOption: questionOption,
            questionType,
            questionDifficulty,
            form: {
                sortId: '',
                type: '',
                difficulty: '',
                score: '',
                topic: '',
                answer: '',
                analysis: '',
                opts: [],
                opt: '',
                xiaoan: '',
                xiaocheck: [],
                topicImage: '',
                topicImageArr: []
            },
            rules: {
                sortId: [
                    { required: true, message: '所属分类必选', trigger: 'change' }
                ],
                type: [
                    { required: true, message: '题型必选', trigger: 'change' }
                ],
                difficulty: [
                    { required: true, message: '难度必选', trigger: 'change' }
                ],
                score: [
                    { required: true, message: '分数必填', trigger: 'blur,change' }
                ],
                topic: [
                    { required: true, message: '题干必填', trigger: 'blur,change' }
                ],
                answer: [
                    { required: true, message: '答案必填', trigger: 'blur,change' }
                ],
                analysis: [
                    { required: true, message: '解析必填', trigger: 'blur,change' }
                ],
                noanswer: [
                    { required: false, message: '解析不必填', trigger: 'blur,change' }
                ],
                xiaoan: [
                    { required: true, message: '正确答案必填', trigger: 'blur,change' }
                ],
                xiaocheck: [
                    { required: true, type: 'array', message: '正确答案必填', trigger: 'blur,change' }
                ]

            }
        }
    },
    methods: {
        up (data, one, index) {
            if (index != 0) {
                var prev = data[index - 1]
                data.splice(index - 1, 1, one)
                data.splice(index, 1, prev)
            }
        },
        down (data, one, index) {
            if (index != (data.length - 1)) {
                var now = one
                var next = data[index + 1]
                data.splice(index, 1, next)
                data.splice(index + 1, 1, now)
            }
        },
        uploadClick (index) {
            console.log(index)
            this.nowIndex = index
            this.$refs.hh.click()
        },
        addOpt (opt, index) {
            console.log(index)
            let newIndex = (this.form.opts.length).toString()
            if (newIndex < 6) {
                this.form.opts.push({ value: '', num: newIndex })
                this.form.topicImageArr.push('')
                console.log(this.form.topicImageArr)
            } else {
                this.$Message.info('最多6个选项')
            }
        },
        delOpt (one, index) {
            this.form.opts.splice(index, 1)
        },
        getType () {
            let params = {
                pageNum: 1,
                pageSize: 999,
                schoolId: '',
                sequence: '',
                sort: '',
                sortId: ''
            }
            sortList(params).then(res => {
                console.log(res)
                this.sList = res.data.data.list.map(item => {
                    return {
                        id: item.sortId,
                        name: item.sort
                    }
                })
            })
        },
        handleAddSort () {
            this.nextPageReload()
            this.$router.push({ name: 'testQuestionsSort' })
        },
        submit () {
            let vm = this
            this.$refs.form.validate(v => {
                if (v) {
                    var a = ''
                    var b = []
                    if (this.form.type == 1 || this.form.type == 2) {
                        b = this.form.opts.map(item => {
                            return item.value
                        })
                        console.log(b)
                        a = b.join('|')
                    }
                    var vaString = ''
                    var varr = []
                    if (vm.form.type == 2) {
                        vm.form.opts.map((item, index) => {
                            if (vm.form.xiaocheck.indexOf(index.toString()) > -1) {
                                varr.push(item.value)
                            }
                        })
                        vaString = varr.join('|')
                    }
                    let params = {
                        analysis: this.form.analysis, // 解析
                        answer: this.form.type == 1 ? this.form.opts[this.form.xiaoan].value : this.form.type == 2 ? vaString : this.form.answer, // 答案
                        del: true, // 删除
                        difficulty: this.form.difficulty, // 难度
                        image: this.form.topicImageArr.join('|'), // 图片
                        openStatu: 0, // 公开状态
                        opt: a, // 选项
                        score: this.form.score, // 分数
                        sortId: this.form.sortId, // 所属类型
                        testId: this.form.testId, // 试题id
                        topic: this.form.topic, // 题干
                        topicImage: '', // 题干图片
                        type: this.form.type// 题型
                    }

                    if (this.$route.params.id) {
                        // 修改 editQuestion(params).then(res => {
                        let checkObj = {
                            topic: this.form.topic,
                            testId: this.form.testId ? this.form.testId : ''
                        }
                        getCheck(checkObj).then(res => {
                            if (res.data.code == '0000') {
                                editQuestion(params).then(res => {
                                    this.$refs.form.validate(v => {
                                        if (v) {
                                            if (res.data.code != '0000') {
                                                this.message.error(res.data.data)
                                                return
                                            }
                                            this.$Message.success('保存成功')
                                            this.nextPageReload()
                                            this.$router.push({
                                                name: 'testQuestionsList',
                                                query: {
                                                }
                                            })
                                        }
                                    })
                                })
                            } else {
                                this.$Message.error(this.data.data)
                            }
                        })
                    } else {
                        let checkObj = {
                            topic: this.form.topic
                        }
                        getCheck(checkObj).then(res => {
                            if (res.data.code == '0000') {
                                addQuestion(params).then(res => {
                                    this.$refs.form.validate(v => {
                                        if (v) {
                                            if (res.data.code != '0000') {
                                                this.message.error(res.data.msg)
                                                return
                                            }
                                            this.$Message.success('保存成功')
                                            this.nextPageReload()
                                            this.$router.push({
                                                name: 'testQuestionsList',
                                                query: {
                                                }
                                            })
                                        }
                                    })
                                })
                            } else {
                                this.$Message.error(res.data.data)
                            }
                        })
                    }
                }
            })
        },
        handleCancel () {
            this.$router.go(-1)
        },
        handleRemove (file) {
            const fileList = this.$refs.upload.fileList
            this.$refs.upload.fileList.splice(fileList.indexOf(file), 1)
        },
        handleSuccess (res, file) {
            console.log(res)
            console.log('上传成功')
            console.log(this.form.opts)
            let imgUrl = this.picUrl + res.data
            this.form.topicImageArr[this.nowIndex] = imgUrl
            this.form.topicImageArr.splice(this.nowIndex, 1, this.form.topicImageArr[this.nowIndex])
            // this.$forceUpdate()
            // 把上传成功的图片显示出来
        },
        handleFormatError (file) {
            this.$Notice.warning({
                title: 'The file format is incorrect',
                desc: 'File format of ' + file.name + ' is incorrect, please select jpg or png.'
            })
        },
        handleMaxSize (file) {
            this.$Notice.warning({
                title: 'Exceeding file size limit',
                desc: 'File  ' + file.name + ' is too large, no more than 2M.'
            })
        },
        handleBeforeUpload () {

        }
    },
    mounted () {
        this.getType()
        const id = this.$route.params.id
        let pa = { testId: id }
        let vm = this
        if (id) {
            getQuestion(pa).then(res => {
                console.log(res)
                Object.assign(this.form, res.data.data)
                vm.form.score = res.data.data.score.toString()
                vm.form.type = res.data.data.type.toString()
                vm.form.difficulty = res.data.data.difficulty.toString()
                var list = res.data.data.opt.split('|')
                console.log(list)
                if (vm.form.type == '1' || vm.form.type == '2') {
                    vm.form.opts = list.map((item, index) => {
                        return {
                            value: item,
                            num: index.toString()
                        }
                    })
                    if (res.data.data.image) {
                        vm.form.topicImageArr = res.data.data.image.split('|')
                    }
                    if (vm.form.type == '1') {
                        this.form.opts.map((item, index) => {
                            if (item.value == this.form.answer) {
                                this.form.xiaoan = index.toString()
                            }
                        })
                        this.form.topicImageArr.map((item, index) => {
                            if (item == this.form.answer) {
                                this.form.xiaoan = index.toString()
                            }
                        })
                    } else if (vm.form.type == '2') {
                        var vhh = vm.form.answer.split('|')
                        vm.form.xiaocheck = []
                        vm.form.opts.map((item, index) => {
                            if (vhh.indexOf(item.value) > -1) {
                                vm.form.xiaocheck.push(index.toString())
                            }
                        })
                        this.form.topicImageArr.map((item, index) => {
                            if (vhh.indexOf(item) > -1) {
                                vm.form.xiaocheck.push(index.toString())
                            }
                        })
                    }
                }
            })
        } else {
            this.form.opts.push({ value: '', num: '0' })
            vm.form.topicImageArr.push('')
        }
    }
}
</script>
<style lang="less" scoped>
.nl{

}
.avact-img{
    width:33px;
    height:33px;
}
.ivu-form {
    max-width: 800px;
}
.h30{
    height: 33px;
    line-height: 33px;
    margin-bottom:24px;
}
.ml10{
    margin-left:10px;
}
</style>
<style>
.notop{
    margin-top:0px !important;
}
.nl .ivu-form-item-content{
    margin-left:0px !important;
}
</style>
